package cn.wolfcode.web.controller;

import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.config.AlipayProperties;
import cn.wolfcode.domain.PayVo;
import cn.wolfcode.domain.RefundVo;
import cn.wolfcode.feign.SeckillFeignService;
import cn.wolfcode.web.msg.PayCodeMsg;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


@RestController
@RequestMapping("/alipay")
@Slf4j
@SuppressWarnings("all")
public class AlipayController {
    private final AlipayClient alipayClient;
    private final AlipayProperties alipayProperties;

    private final SeckillFeignService seckillFeignService;

    public AlipayController(AlipayClient alipayClient, AlipayProperties alipayProperties, SeckillFeignService seckillFeignService) {
        this.alipayClient = alipayClient;
        this.alipayProperties = alipayProperties;
        this.seckillFeignService = seckillFeignService;
    }


    @RequestMapping("/refund")
    public Result<Boolean> refund(@RequestBody RefundVo refundVo){
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", refundVo.getOutTradeNo());
        bizContent.put("refund_amount", refundVo.getRefundAmount());
        bizContent.put("out_request_no", refundVo.getRefundReason());

        try {
            request.setBizContent(bizContent.toString());
            AlipayTradeRefundResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                if ("Y".equals(response.getFundChange())) {
                    // 退款成功
                    log.info("[支付宝退款] 退款成功, 订单号:{}", refundVo.getOutTradeNo());
                    return Result.success(true);
                } else {
                    // 退款处理中
                    log.info("[支付宝退款] 退款处理中, 订单号:{}", refundVo.getOutTradeNo());
                    // 查询退款状态
                    boolean refundQuery = this.refundQuery(refundVo.getOutTradeNo(), response.getTradeNo());
                    return Result.success(refundQuery);
                }
            }
        } catch (AlipayApiException e) {
            log.error("[支付宝退款] 退款失败, 订单号:{},错误信息:{}", refundVo.getOutTradeNo(), e.getStackTrace());
            return Result.success(false);
        }
        return Result.success(false);
    }

    private boolean refundQuery(String outTradeNo,String outRequestNo){
        AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", outTradeNo);
        bizContent.put("out_request_no", outRequestNo);
        request.setBizContent(bizContent.toString());
        log.info("[支付宝退款] 退款查询, 订单号:{}", outTradeNo);
        try {
            AlipayTradeFastpayRefundQueryResponse response = alipayClient.execute(request);
            if (!response.isSuccess()) {
                return false;
            }
        } catch (AlipayApiException e) {
            return false;
        }

        return true;
    }


    @RequestMapping
    public Result<String> payment(String orderNo) {
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());
        alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
        // 商户订单号
        Result<PayVo> payVoByOrderNo = seckillFeignService.findPayVoByOrderNo(orderNo);
        PayVo payVo = payVoByOrderNo.getData(true);

        JSONObject json = new JSONObject();
        json.put("out_trade_no", payVo.getOutTradeNo());
        //付款金额，必填
        json.put("total_amount", payVo.getTotalAmount());
        //订单名称，必填
        json.put("subject", payVo.getSubject());
        //商品描述，可空
        json.put("body", payVo.getBody());
        json.put("product_code", "FAST_INSTANT_TRADE_PAY");

        alipayRequest.setBizContent(json.toJSONString());

        // 发起支付请求
        try {
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            log.info("[支付宝支付] 发起支付请求, 订单号:{}, 返回结果:{}", payVo.getOutTradeNo(), result);
            return Result.success(result);
        } catch (AlipayApiException e) {
            log.error("[支付宝支付] 支付失败订单号:{},错误信息:{}", payVo.getOutTradeNo(), e.getStackTrace());
            throw new BusinessException(PayCodeMsg.PAY_ERROR);
        }
    }

    @RequestMapping("/return_url")
    public void returnUrl(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> params = this.resolveParams(request);
        // 检查参数签名是否正确
        try {
            boolean checkV1 = AlipaySignature.rsaCheckV1(params,
                    alipayProperties.getAlipayPublicKey(),
                    alipayProperties.getCharset(),
                    alipayProperties.getSignType());
            if (checkV1) {
                String orderNo = params.get("out_trade_no");
                // 验证签名成功
                log.info("[支付宝支付] 验证签名成功, 订单号:{}", orderNo);
                // 跳转到支付成功页面
                response.sendRedirect(String.format(alipayProperties.getRedirectUrl(), orderNo));
            }
        } catch (Exception e) {
            log.error("[支付宝支付] 验证签名失败, 订单号:{},错误信息:{}", params.get("out_trade_no"), e.getStackTrace());
            throw new BusinessException(PayCodeMsg.PAY_ERROR);
        }
    }


    @RequestMapping("/notify_url")
    public String notifyUrl(HttpServletRequest request) {
        Map<String, String> params = this.resolveParams(request);
        // 检查参数签名是否正确
        try {
            boolean checkV1 = AlipaySignature.rsaCheckV1(params,
                    alipayProperties.getAlipayPublicKey(),
                    alipayProperties.getCharset(),
                    alipayProperties.getSignType());
            if (checkV1) {
                // 验证签名成功
                log.info("[支付宝支付] 验证签名成功, 订单号:{}", params.get("out_trade_no"));
                // 商户订单号
                String outTradeNo = params.get("out_trade_no");
                // 支付宝交易号
                String tradeNo = params.get("trade_no");
                // 交易状态
                String tradeStatus = params.get("trade_status");
                // App ID
                String appId = params.get("app_id");
                // 支付金额
                String totalAmount = params.get("total_amount");
                if (!alipayProperties.getAppId().equals(appId)) {
                    log.error("[支付宝支付] 验证签名失败, 订单号:{},错误信息:{}", params.get("out_trade_no"), "App ID不一致");
                    return "fail";
                }
                if (tradeStatus.equals("TRADE_FINISHED")) {
                    // 退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                    log.info("[支付宝支付] 支付成功, 订单号:{}", params.get("out_trade_no"));
                } else if (tradeStatus.equals("TRADE_SUCCESS")) {
                    // 付款完成后，支付宝系统发送该交易状态通知
                    Result<?> result = seckillFeignService.paySuccess(outTradeNo, tradeNo,totalAmount);
                    if (result.hasError()) {
                        log.error("[支付宝支付] 支付失败, 订单号:{},错误信息:{}", params.get("out_trade_no"), result.getMsg());
                        return "fail";
                    }
                }
                return "success";
            }

        } catch (AlipayApiException e) {
            log.error("[支付宝支付] 验证签名失败, 订单号:{},错误信息:{}", params.get("out_trade_no"), e.getStackTrace());
        }
        return "fail";
    }


    private Map<String, String> resolveParams(HttpServletRequest request) {
        //获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        return params;
    }
}